package com.marvels.financial.loan.service.impl;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.marvels.approve.loan.dao.IMcamLoanApplyInfoDao;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.constants.PageConstant;
import com.marvels.common.constants.RedisKeyConstant;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.collection.dao.OverdueCollectTaskDao;
import com.marvels.financial.loan.dao.McfeAdjustmentFeeDao;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dao.McfeCustomerRepaymentPlanDao;
import com.marvels.financial.loan.dao.McfePaymentWithholdDetailDao;
import com.marvels.financial.loan.dao.McfeRepaymentFlowDao;
import com.marvels.financial.loan.dao.McfeReversalDetailDao;
import com.marvels.financial.loan.dao.McfeTransactionCodeDao;
import com.marvels.financial.loan.dto.AdjustmentFeeReviewDto;
import com.marvels.financial.loan.dto.McfeAdjustmentFeeDTO;
import com.marvels.financial.loan.dto.McfeCustomerLoanContractDTO;
import com.marvels.financial.loan.dto.McfeCustomerRepaymentPlanDTO;
import com.marvels.financial.loan.dto.McfePaymentWithholdDetailDTO;
import com.marvels.financial.loan.dto.McfeRepaymentFlowDTO;
import com.marvels.financial.loan.dto.McfeReversalDetailDTO;
import com.marvels.financial.loan.dto.McfeTransactionCodeDTO;
import com.marvels.financial.loan.dto.PenaltyAdjustConditionDto;
import com.marvels.financial.loan.dto.PenaltyAdjustDto;
import com.marvels.financial.loan.service.PenaltyAdjustmentApi;
import com.marvels.financial.utils.FinancialUtil;
import com.marvels.loanapply.dao.AcLoanApplyInfoDao;
import com.marvels.loanapply.dto.AcLoanApplyInfoDTO;

import cn.hutool.core.util.StrUtil;

@Service
public class PenaltyAdjustmentImpl implements PenaltyAdjustmentApi{

	@Autowired
	private McfeCustomerRepaymentPlanDao mcfeCustomerRepaymentPlanDao;
	
	@Autowired
	private McfeAdjustmentFeeDao mcfeAdjustmentFeeDao;
	
	@Autowired
	private McfeTransactionCodeDao codeDao;
	
	@Autowired
	private McfeCustomerRepaymentPlanDao planDao;
	
	@Autowired
	private McfeReversalDetailDao detailDao;
	
	@Autowired
	private McfePaymentWithholdDetailDao mcfePaymentWithholdDetailDao;
	
	@Autowired
	private McfeCustomerLoanContractDao contractDao;
	
	@Autowired
	private IMcamLoanApplyInfoDao iMcamLoanApplyInfoDao;
	@Autowired
	private AcLoanApplyInfoDao acLoanApplyInfoDao;
	@Autowired
	private OverdueCollectTaskDao overdueCollectTaskDao;
	@Autowired
	private McfeRepaymentFlowDao flowDao;
	@Override
	public Page<PenaltyAdjustDto> penaltyAdjustmentList(PenaltyAdjustConditionDto dto)  throws MarvelsBusinessException{
		int pageSize=dto.getPageSize();
		int pageNum=dto.getPageNum();
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);
		Page<PenaltyAdjustDto> dataList = mcfeCustomerRepaymentPlanDao.selectPenaltyAdjustmentList(dto);
		return dataList;
	}

	@Override
	public Page<McfeAdjustmentFeeDTO> penaltyAdjustmentHistory(PenaltyAdjustConditionDto dto)
			throws MarvelsBusinessException {
		int pageSize=dto.getPageSize();
		int pageNum=dto.getPageNum();
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);
		PageHelper.startPage(pageNum,pageSize);
		Page<McfeAdjustmentFeeDTO> dataList = mcfeAdjustmentFeeDao.selectListByPlanId(dto.getPlanId());
		return dataList;
	}

	@Override
	public void penaltyAdjustmentApply(PenaltyAdjustConditionDto dto) throws MarvelsBusinessException {
		if (StringUtils.isEmpty(dto.getAdjustAmount()) || Double.parseDouble(dto.getAdjustAmount()) == 0) {
			throw new MarvelsBusinessException("请输入调整金额");
		}
		if (StringUtils.isEmpty(dto.getTransactionCode())) {
			throw new MarvelsBusinessException("请选择交易类型");
		}
		if (StringUtils.isEmpty(dto.getRemarks())) {
			throw new MarvelsBusinessException("请填写备注");
		}

		Page<PenaltyAdjustDto> dataList = mcfeCustomerRepaymentPlanDao.selectPenaltyAdjustmentList(dto);
		if (null == dataList || dataList.size() < 1) {
			throw new MarvelsBusinessException("该还款计划不存在");
		}

		// 判断还款计划的状态
		if ("2".equals(dataList.get(0).getStatus()) || "3".equals(dataList.get(0).getStatus())
				|| "10".equals(dataList.get(0).getStatus())) {
			throw new MarvelsBusinessException("该还款计划不在还款状态");
		}

		PenaltyAdjustDto data = dataList.get(0);
		BigDecimal adjustAmount = new BigDecimal(dto.getAdjustAmount());
		if ("management_fee_reducte".equalsIgnoreCase(dto.getTransactionCode())) {// 管理费-减免
			if (adjustAmount.compareTo(data.getRemainManagementFee()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}
		if ("penalty_fee_reducte".equalsIgnoreCase(dto.getTransactionCode())) {// 违约金减免
			if (adjustAmount.compareTo(data.getRemainPenaltyFee()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}
		if ("late_fee_reducte".equalsIgnoreCase(dto.getTransactionCode())) {// 滞纳金-减免
			if (adjustAmount.compareTo(data.getRemainLateFeeAct()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}
		if ("principal_reducte".equalsIgnoreCase(dto.getTransactionCode())) {// 本金-减免
			if (adjustAmount.compareTo(data.getRemainPrincipalFee()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}
		if ("management_fee_increase".equalsIgnoreCase(dto.getTransactionCode())) {// 管理费-调增
			if (adjustAmount.compareTo(data.getIncreaseManagementFee()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}
		if ("penalty_fee_increase".equalsIgnoreCase(dto.getTransactionCode())) {// 违约金-调增
			if (adjustAmount.compareTo(data.getIncreasePenaltyFee()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}
		if ("late_fee_increase".equalsIgnoreCase(dto.getTransactionCode())) {// 滞纳金-调增
			if (adjustAmount.compareTo(data.getIncreaseLateFeeAct()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}
		if ("principal_increase".equalsIgnoreCase(dto.getTransactionCode())) {// 本金-调增
			if (adjustAmount.compareTo(data.getIncreasePrincipalFee()) == 1) {
				throw new MarvelsBusinessException("调整金额不能大于最大调整金额");
			}
		}

		String loanId = data.getLoanId();
		// 加锁 避免重复插入数据
		String key = RedisKeyConstant.HAND_PAYMENT_WITHHOLD + loanId;
		boolean isNotLock = false;
		try {
			isNotLock = CacheUtils.isNotLock(key, loanId);
			if (isNotLock) {
				// 先将这个key设置过期时间
				CacheUtils.setExpire(key, 60);
				// 判断是否存在待审批的申请
				int count = mcfeAdjustmentFeeDao.countApplyingByPlanId(dto.getPlanId(), "0");
				if (count > 0) {
					throw new MarvelsBusinessException("存在待审批的申请请稍候再试");
				}
				// 判断还款计划对应的进件是否有处在正在冲账中的流水
				McfeRepaymentFlowDTO flowDTO = flowDao.selectDealingByLoanId(loanId);
				if (flowDTO != null) {
					MarvelsLogUtil.getInstance().info(">>>>>>>>>>loanId:" + loanId + ",有处在冲账中或未冲账的流水");
					throw new MarvelsBusinessException("存在未冲账的流水,请稍候再试");
				}
				McfePaymentWithholdDetailDTO detailDTO = mcfePaymentWithholdDetailDao.selectTradingByLoanId(loanId);
				if (detailDTO != null) {
					MarvelsLogUtil.getInstance()
					.info(">>>>>>>>>>loanId:" + loanId + ",存在处理中的代扣");
					throw new MarvelsBusinessException("存在处理中的代扣请稍候再试");
				}
				// 持久化审核申请信息
				UserDTO user = CacheUtils.getCacheUser();
				McfeAdjustmentFeeDTO adjustDto = new McfeAdjustmentFeeDTO();
				adjustDto.setAmount(adjustAmount);
				adjustDto.setCreatedBy(user.getUserName());
				adjustDto.setCreatedDate(new Date());
				adjustDto.setTransactionCode(dto.getTransactionCode());
				adjustDto.setTransactionName(dto.getTransactionName());
				adjustDto.setCustName(data.getCustName());
				adjustDto.setCustCardNo(data.getCustIdNumber());
				adjustDto.setLoanId(data.getLoanId());
				adjustDto.setStatus("0");// 调整交易状态 0待审批 1审批成功 2审批拒绝
				adjustDto.setPlanCode(data.getPlanId());
				adjustDto.setRemark(dto.getRemarks());
				adjustDto.setUpdatedBy(user.getUserName());
				adjustDto.setUpdatedDate(new Date());
				int insertCount = mcfeAdjustmentFeeDao.insertSelective(adjustDto);
				if (insertCount < 1) {
					throw new MarvelsBusinessException("持久化审核申请信息异常");
				}
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>loanId:" + loanId + ",代还款申请异常:", e);
			throw new MarvelsBusinessException(e.getMessage());
		} finally {
			if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
				CacheUtils.del(key);
			}
		}
		
	}

	@Override
	public Page<AdjustmentFeeReviewDto> penaltyAdjustmentReview(PenaltyAdjustConditionDto dto)
			throws MarvelsBusinessException {
		int pageSize=dto.getPageSize();
		int pageNum=dto.getPageNum();
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);
		dto.setAdjustStatus("0");
		Page<AdjustmentFeeReviewDto> dataList = mcfeAdjustmentFeeDao.selectReviewList(dto);
		return dataList;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public synchronized void penaltyAdjustmentAdopt(PenaltyAdjustConditionDto dto) throws MarvelsBusinessException {
		Page<PenaltyAdjustDto> dataList = mcfeCustomerRepaymentPlanDao.selectPenaltyAdjustmentList(dto);
		if(null==dataList || dataList.size()<1){
			throw new MarvelsBusinessException("该还款计划不存在");
		}
		//判断还款计划的状态
		if("2".equals(dataList.get(0).getStatus())|| "3".equals(dataList.get(0).getStatus()) || "10".equals(dataList.get(0).getStatus())){
			throw new MarvelsBusinessException("该还款计划不在还款状态");
		}
		
		//判断计划id是否在待审批状态
		McfeAdjustmentFeeDTO feeDTO =mcfeAdjustmentFeeDao.selectDtoByPlanId(dto.getPlanId());
		if(feeDTO==null || !"0".equals(feeDTO.getStatus())){
			throw new MarvelsBusinessException("申请不在待审批状态");
		}
		if(feeDTO.getAmount()==null || feeDTO.getAmount().compareTo(BigDecimal.ZERO)<=0) {
			throw new MarvelsBusinessException("申请减免金额必须大于0");
		}
		
		//更新审核表记录
		UserDTO user = CacheUtils.getCacheUser();
		McfeAdjustmentFeeDTO adjustmentFeeDTO =new McfeAdjustmentFeeDTO ();
		adjustmentFeeDTO.setApprovalTime(new Date());
		adjustmentFeeDTO.setStatus("1");//审批成功
		adjustmentFeeDTO.setOrginStatus("0");//审核中
		adjustmentFeeDTO.setUpdatedBy(user.getUserName());
		adjustmentFeeDTO.setUpdatedDate(new Date());
		adjustmentFeeDTO.setPlanCode(dto.getPlanId());
		int updateCount=mcfeAdjustmentFeeDao.updateMcfeAdjustmentFeeDTO(adjustmentFeeDTO);
		if(updateCount<1){
			throw new MarvelsBusinessException("更新申请状态异常");
		}
			
		//从数据库中获取还款计划
		McfeCustomerRepaymentPlanDTO planDTO= mcfeCustomerRepaymentPlanDao.selectPlanByPlanCode(dto.getPlanId());
		//合同表数据
		McfeCustomerLoanContractDTO contractDTO = contractDao.selectContractByLoanId(planDTO.getLoanId());
		
		//费用调整
		this.adjustDeal(dto,feeDTO,contractDTO,planDTO);
		
		planDTO.setUpdatedBy(user.getUserCode());
		planDTO.setUpdatedDate(new Date());
		//本期结清检查
		if(FinancialUtil.checkPlanStatus(planDTO)) {
			planDTO.setStatus(2);
			planDTO.setPaymentDateAct(new Date());
		}
		int count=planDao.updatePlanWaiveData(planDTO);
		if(count<1){
			throw new MarvelsBusinessException("更新还款计划失败");
		}
		
		//更新合同表
		contractDTO.setUpdatedBy(user.getUserCode());
		contractDTO.setUpdatedDate(new Date());
		
		//检查合同状态是否结清
		if (FinancialUtil.checkContract(contractDTO)) {
			contractDTO.setStatus(2);
			contractDTO.setDelqDays(0);
			contractDTO.setForceFlag(MarvelsConstant.FORCE_COLLECTION_FLAG_A0);
		}
		int contractCount = contractDao.updateWaiveByContractId(contractDTO);
		if (contractCount < 1) {
			throw new MarvelsBusinessException("更新合同失败");
		} 
		if(contractDTO.getStatus()==2){//已经还完  更新ac_loan_apply_info表状态   更新mcam_loan_apply_info表状态
			//修改进件表中的实际放款金额
			com.marvels.approve.loan.dto.McamLoanApplyInfoDTO mcamLoanApplyInfoDTO=new com.marvels.approve.loan.dto.McamLoanApplyInfoDTO();
			mcamLoanApplyInfoDTO.setLoanId(planDTO.getLoanId());
			mcamLoanApplyInfoDTO.setUpdatedBy(user.getUserCode());
			mcamLoanApplyInfoDTO.setUpdatedDate(new Date());
			mcamLoanApplyInfoDTO.setStatus(LoanStateConstant.A00);
			iMcamLoanApplyInfoDao.updateByLoanId(mcamLoanApplyInfoDTO);
			
			//修改ac_loan表中的时间放款金额
			AcLoanApplyInfoDTO acLoanApplyInfoDTO=new AcLoanApplyInfoDTO();
			acLoanApplyInfoDTO.setUpdateTime(new Date());
			acLoanApplyInfoDTO.setLoanId(planDTO.getLoanId());
			acLoanApplyInfoDTO.setStatus(LoanStateConstant.A00);
			acLoanApplyInfoDao.modifyAcLoanApplyInfo(acLoanApplyInfoDTO);
		}
		
		//当还款计划状态变为正常或结清时修改催收表状态
		/*if((planDTO.getStatus()==MarvelsConstant.CONTRACT_ACCOUNT_STATUS_NORMAL || planDTO.getStatus()==MarvelsConstant.PAYMENT_PLAN_STATUS_COMPLETE)
				&& StrUtil.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
			try {
				overdueCollectTaskDao.urgentByLoanId(planDTO.getLoanId());
			}catch(Exception ex) {
				MarvelsLogUtil.getInstance().error("更新催收记录为出催失败,loanId=" + planDTO.getLoanId(),ex);
			}
		}*/
		//插入mcfe_reversal_detail冲账明细记录
		McfeReversalDetailDTO detailDTO=new McfeReversalDetailDTO();
		detailDTO.setCustCardNo(dataList.get(0).getCustIdNumber());
		detailDTO.setCustName(dataList.get(0).getCustName());
		detailDTO.setMobile(dataList.get(0).getMobile());
		detailDTO.setLoanId(dto.getPlanId());
		detailDTO.setTransactionCode(feeDTO.getTransactionCode());
		detailDTO.setTransactionName(feeDTO.getTransactionName());
		detailDTO.setAmount(feeDTO.getAmount());
		detailDTO.setRemark(feeDTO.getRemark());
		detailDTO.setTransationDate(new Date());
		detailDTO.setPlanCode(dto.getPlanId());
		detailDTO.setCreatedBy(user.getUserName());
		detailDTO.setCreatedDate(new Date());
		detailDTO.setUpdatedBy(user.getUserName());
		detailDTO.setUpdatedDate(new Date());
		int detailCount=detailDao.insertReversalDetail(detailDTO);
		if(detailCount<1){
			throw new MarvelsBusinessException("持久化冲账明细记录失败");
		}
		
	} 
	

	/**
	 * 调整处理
	 * @param feeDTO
	 * @param contractDTO
	 * @param planDTO
	 */
	private void adjustDeal(PenaltyAdjustConditionDto dto,McfeAdjustmentFeeDTO feeDTO,McfeCustomerLoanContractDTO contractDTO,McfeCustomerRepaymentPlanDTO planDTO){
		planDTO.setPlanCode(dto.getPlanId());
		if("management_fee_reducte".equalsIgnoreCase(feeDTO.getTransactionCode())){//管理费
			BigDecimal managementFeeWaive = planDTO.getManagementFeeWaive() == null?BigDecimal.ZERO:planDTO.getManagementFeeWaive();
			planDTO.setManagementFeeWaive(managementFeeWaive.add(feeDTO.getAmount()));//原来减免的+现在减免的
			//减免
			BigDecimal contractManagementFeeWaive = contractDTO.getManagementFeeWaive()==null?BigDecimal.ZERO:contractDTO.getManagementFeeWaive();
			contractDTO.setManagementFeeWaive(contractManagementFeeWaive.add(feeDTO.getAmount()));
			//未还
			BigDecimal managementFeeOs = contractDTO.getManagementFeeOs()==null?BigDecimal.ZERO:contractDTO.getManagementFeeOs();
			contractDTO.setManagementFeeOs(managementFeeOs.subtract(feeDTO.getAmount()));
//			//已还
//			BigDecimal managementFee = contractDTO.getManagementFee() == null?BigDecimal.ZERO:contractDTO.getManagementFee();
//			contractDTO.setManagementFee(managementFee.add(feeDTO.getAmount()));
		}else if("penalty_fee_reducte".equalsIgnoreCase(feeDTO.getTransactionCode())){
			BigDecimal penaltyFeeWaive = planDTO.getPenaltyFeeWaive()==null?BigDecimal.ZERO:planDTO.getPenaltyFeeWaive();
			planDTO.setPenaltyFeeWaive(penaltyFeeWaive.add(feeDTO.getAmount()));
			//减免
			BigDecimal contractPenaltyFeeWaive = contractDTO.getPenaltyFeeWaive()==null?BigDecimal.ZERO:contractDTO.getPenaltyFeeWaive();
			contractDTO.setPenaltyFeeWaive(contractPenaltyFeeWaive.add(feeDTO.getAmount()));
			//未还
			BigDecimal contractPenaltyFeeOs = contractDTO.getPenaltyFeeOs() == null?BigDecimal.ZERO:contractDTO.getPenaltyFeeOs();
			contractDTO.setPenaltyFeeOs(contractPenaltyFeeOs.subtract(feeDTO.getAmount()));
			//已还
//			BigDecimal contractPenaltyFee = contractDTO.getPenaltyFee()==null?BigDecimal.ZERO:contractDTO.getPenaltyFee();
//			contractDTO.setPenaltyFee(contractPenaltyFee.add(feeDTO.getAmount()));
		}else if("late_fee_reducte".equalsIgnoreCase(feeDTO.getTransactionCode())){
			BigDecimal lateFeeWaive = planDTO.getLateFeeWaive()==null?BigDecimal.ZERO:planDTO.getLateFeeWaive();
			planDTO.setLateFeeWaive(lateFeeWaive.add(feeDTO.getAmount()));
			//减免
			BigDecimal contractLateFeeWaive = contractDTO.getLateFeeWaive() == null?BigDecimal.ZERO:contractDTO.getLateFeeWaive();
			contractDTO.setLateFeeWaive(contractLateFeeWaive.add(feeDTO.getAmount()));
			//未还
			BigDecimal contractLateFeeOS = contractDTO.getLateFeeOs() == null?BigDecimal.ZERO:contractDTO.getLateFeeOs();
			contractDTO.setLateFeeOs(contractLateFeeOS.subtract(feeDTO.getAmount()));
//			//已还
//			BigDecimal contractLateFee = contractDTO.getLateFee()==null?BigDecimal.ZERO:contractDTO.getLateFee();
//			contractDTO.setLateFee(contractLateFee.add(feeDTO.getAmount()));
		}else if("principal_reducte".equalsIgnoreCase(feeDTO.getTransactionCode())){
			BigDecimal principalWaive = planDTO.getPrincipalWaive()==null?BigDecimal.ZERO:planDTO.getPrincipalWaive();
			planDTO.setPrincipalWaive(principalWaive.add(feeDTO.getAmount()));
			//减免
			BigDecimal contractPrincipalWaive = contractDTO.getPrincipalWaive() == null?BigDecimal.ZERO:contractDTO.getPrincipalWaive();
			contractDTO.setPrincipalWaive(contractPrincipalWaive.add(feeDTO.getAmount()));
			//未还
			BigDecimal contractPrincipalOS = contractDTO.getPrincipalOs() == null?BigDecimal.ZERO:contractDTO.getPrincipalOs();
			contractDTO.setPrincipalOs(contractPrincipalOS.subtract(feeDTO.getAmount()));
//			//已还
//			BigDecimal contractPrincipal = contractDTO.getPrincipal()==null?BigDecimal.ZERO:contractDTO.getPrincipal();
//			contractDTO.setPrincipal(contractPrincipal.add(feeDTO.getAmount()));
		}else if("management_fee_increase".equalsIgnoreCase(feeDTO.getTransactionCode())){//管理费调增
			BigDecimal managementFeeWaive = planDTO.getManagementFeeWaive()==null?BigDecimal.ZERO:planDTO.getManagementFeeWaive();
			if(managementFeeWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal subMoney = managementFeeWaive.subtract(feeDTO.getAmount());
				planDTO.setManagementFeeWaive(subMoney.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO:subMoney);
			}
			//调增
			BigDecimal contractManagementFeeWaive = contractDTO.getManagementFeeWaive() == null?BigDecimal.ZERO:contractDTO.getManagementFeeWaive();
			if(contractManagementFeeWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal contractsubMoney = contractManagementFeeWaive.subtract(feeDTO.getAmount());
				contractDTO.setManagementFeeWaive(contractsubMoney.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:contractsubMoney);
			}
			//未还
			BigDecimal contractManagementFeeOs = contractDTO.getManagementFeeOs() == null?BigDecimal.ZERO:contractDTO.getManagementFeeOs();
			contractDTO.setManagementFeeOs(contractManagementFeeOs.add(feeDTO.getAmount()));
		}else if("penalty_fee_increase".equalsIgnoreCase(feeDTO.getTransactionCode())){
			BigDecimal penaltyFeeWaive = planDTO.getPenaltyFeeWaive()==null?BigDecimal.ZERO:planDTO.getPenaltyFeeWaive();
			if(penaltyFeeWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal subMoney = penaltyFeeWaive.subtract(feeDTO.getAmount());
				planDTO.setPenaltyFeeWaive(subMoney.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:subMoney);
			}
			//调增
			BigDecimal contractPenaltyFeeWaive = contractDTO.getPenaltyFeeWaive() == null?BigDecimal.ZERO:contractDTO.getPenaltyFeeWaive();
			if(contractPenaltyFeeWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal contractsubMoney = contractPenaltyFeeWaive.subtract(feeDTO.getAmount());
				contractDTO.setPenaltyFeeWaive(contractsubMoney.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:contractsubMoney);
			}
			//未还
			BigDecimal contractPenaltyFeeOs = contractDTO.getPenaltyFeeOs() == null?BigDecimal.ZERO:contractDTO.getPenaltyFeeOs();
			contractDTO.setPenaltyFeeOs(contractPenaltyFeeOs.add(feeDTO.getAmount()));
		}else if("late_fee_increase".equalsIgnoreCase(feeDTO.getTransactionCode())){
			BigDecimal lateFeeWaive = planDTO.getLateFeeWaive()==null?BigDecimal.ZERO:planDTO.getLateFeeWaive();
			if(lateFeeWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal subMoney = lateFeeWaive.subtract(feeDTO.getAmount());
				planDTO.setLateFeeWaive(subMoney.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:subMoney);
			}
			//增调
			BigDecimal contractLateFeeWaive = contractDTO.getLateFeeWaive() == null?BigDecimal.ZERO:contractDTO.getLateFeeWaive();
			if(contractLateFeeWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal contractsubMoney = contractLateFeeWaive.subtract(feeDTO.getAmount());
				contractDTO.setLateFeeWaive(contractsubMoney.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:contractsubMoney);
			}
			//未还
			BigDecimal contractLateFeeOs = contractDTO.getLateFeeOs() == null?BigDecimal.ZERO:contractDTO.getLateFeeOs();
			contractDTO.setLateFeeOs(contractLateFeeOs.add(feeDTO.getAmount()));
		}else if("principal_increase".equalsIgnoreCase(feeDTO.getTransactionCode())){
			BigDecimal principalWaive = planDTO.getPrincipalWaive()==null?BigDecimal.ZERO:planDTO.getPrincipalWaive();
			if(principalWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal subMoney = principalWaive.subtract((feeDTO.getAmount()));
				planDTO.setPrincipalWaive(subMoney.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:subMoney);
			}
			//调增
			BigDecimal contractPrincipalWaive = contractDTO.getPrincipalWaive() == null?BigDecimal.ZERO:contractDTO.getPrincipalWaive();
			if(contractPrincipalWaive.compareTo(BigDecimal.ZERO)>0){
				BigDecimal contractsubMoney = contractPrincipalWaive.subtract(feeDTO.getAmount());
				contractDTO.setPrincipalWaive(contractsubMoney.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:contractsubMoney);
			}
			//未还
			BigDecimal contractPrincipalOs = contractDTO.getPrincipalOs() == null?BigDecimal.ZERO:contractDTO.getPrincipalOs();
			contractDTO.setPrincipalOs(contractPrincipalOs.add(feeDTO.getAmount()));
		}
		
	}
	
	
	
	@Override
	public void penaltyAdjustmentRefuse(PenaltyAdjustConditionDto dto) throws MarvelsBusinessException {
		Page<PenaltyAdjustDto> dataList = mcfeCustomerRepaymentPlanDao.selectPenaltyAdjustmentList(dto);
		if(null==dataList || dataList.size()<1){
			throw new MarvelsBusinessException("该还款计划不存在");
		}
		//判断还款计划的状态
		if("2".equals(dataList.get(0).getStatus())|| "3".equals(dataList.get(0).getStatus()) || "10".equals(dataList.get(0).getStatus())){
			throw new MarvelsBusinessException("该还款计划不在还款状态");
		}
		
		//判断计划id是否在待审批状态
		int count =mcfeAdjustmentFeeDao.countApplyingByPlanId(dto.getPlanId(),"0");
		if(count<1){
			throw new MarvelsBusinessException("申请不在待审批状态");
		}
		//更新审核表记录
		UserDTO user = CacheUtils.getCacheUser();
		McfeAdjustmentFeeDTO adjustmentFeeDTO =new McfeAdjustmentFeeDTO ();
		adjustmentFeeDTO.setApprovalTime(new Date());
		adjustmentFeeDTO.setStatus("2");//拒绝
		adjustmentFeeDTO.setOrginStatus("0");//审核中
		adjustmentFeeDTO.setUpdatedBy(user.getUserName());
		adjustmentFeeDTO.setUpdatedDate(new Date());
		adjustmentFeeDTO.setPlanCode(dto.getPlanId());
		int updateCount=mcfeAdjustmentFeeDao.updateMcfeAdjustmentFeeDTO(adjustmentFeeDTO);
		if(updateCount<1){
			throw new MarvelsBusinessException("更新申请状态失败");
		}
	}

	@Override
	public List<McfeTransactionCodeDTO> queryCodeList() throws MarvelsBusinessException {
		List<McfeTransactionCodeDTO> list =null;
		String key="PENALTY_ADJUST_TRANSACTION_CODE_KEY";
		Object object=CacheUtils.getCacheObject(key);
		if(object!=null){
			list=(List<McfeTransactionCodeDTO>)object;
		}
		if(CollectionUtils.isEmpty(list)){
			McfeTransactionCodeDTO transactionCodeDTO=new McfeTransactionCodeDTO();
			transactionCodeDTO.setTransactionType("1");//交易类型，1-罚息调整  20-还款\n            40-投标\n            60-费用\n
			list=codeDao.queryCodeList(transactionCodeDTO);
			CacheUtils.cacheObject(key, list);
		}
		return list;
	}

	@Override
	public Page<AdjustmentFeeReviewDto> penaltyAdjustmentQuery(PenaltyAdjustConditionDto dto)
			throws MarvelsBusinessException {
		int pageSize=dto.getPageSize();
		int pageNum=dto.getPageNum();
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);
		Page<AdjustmentFeeReviewDto> dataList = mcfeAdjustmentFeeDao.selectReviewList(dto);
		return dataList;
	} 
}
